package com.zhongkai.fileHashUtil;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

public class FileHashUtil {
	private static final String[] HASH_TYPES = { "MD2", "MD5", "SHA1", "SHA-256", "SHA-384", "SHA-512" };

	public static void FileMD5( String fileName ) throws NoSuchAlgorithmException, IOException {
		System.out.println( "需要获取hash的文件为：　" + fileName );
		List<MessageDigest> mds = new ArrayList<MessageDigest>( );
		for ( String hashType : HASH_TYPES ) {
			mds.add( MessageDigest.getInstance( hashType ) );
		}

		InputStream in = null;
		try {
			in = new FileInputStream( fileName );
			byte[] buffer = new byte[1024];
			int count = 0;
			while ( ( count = in.read( buffer ) ) > 0 ) {
				for ( MessageDigest md : mds ) {
					md.update( buffer, 0, count );
				}
			}
		} catch ( FileNotFoundException e ) {
			e.printStackTrace( );
		} catch ( SecurityException e ) {
			e.printStackTrace( );
		} finally {
			if ( null != in ) {
				in.close( );
			}
		}

		for ( MessageDigest md : mds ) {
			System.out.println( md.getAlgorithm( ) + " == " + Str2Hex( md.digest( ) ) );
		}
	}

	private static String Str2Hex( byte[] src ) {
		final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		int length = src.length;
		StringBuilder builder = new StringBuilder( length * 2 );
		for ( int i = 0; i < length; i++ ) {
			builder.append( HEX_CHAR[src[i] & 0xF0 >>> 4] );
			builder.append( HEX_CHAR[src[i] & 0x0F] );
		}
		return builder.toString( );
	}
}
